package com.starrysky.cakestore.dao;

import com.starrysky.cakestore.entity.Type;

import java.sql.*;
import java.util.*;

public class TypeDao {

    static {
        //加载驱动
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
    }

    public static Connection getCon(){
        try {
            //获取数据库连接
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cakeshop_db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8",
                    "root",
                    "xjl13615875481"
            );

            return con;

        }catch (SQLException e){
            e.printStackTrace();
            return null;
        }
    }


    public LinkedHashMap<Type, List<Type>>  findAll(){
        LinkedHashMap<Type,List<Type>>typeMap = new LinkedHashMap<>();
        HashMap<Integer,Type>parentType = new HashMap<>();

        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection con = getCon();
        String sql1 = "select * from tbl_type where parentId is null";
        String sql2 = "select * from tbl_type where parentId is not null";

        try {
            ps = con.prepareStatement(sql1);
            rs = ps.executeQuery();

            while (rs.next()){
                Integer id = rs.getInt("id");
                String name = rs.getString("name");
                Integer parentId = null;

                Type type = new Type(id,name,parentId);

                parentType.put(id,type);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }

        try {
            ps = con.prepareStatement(sql2);
            rs = ps.executeQuery();

            while (rs.next()){
                Integer id = rs.getInt("id");
                String name = rs.getString("name");
                Integer parentId = rs.getInt("parentId");

                Type type = new Type(id,name,parentId);

                Type parent = parentType.get(parentId);

                List<Type> childTypes = typeMap.get(parent);

                if(childTypes==null)childTypes=new ArrayList<>();

                childTypes.add(type);

                typeMap.put(parent,childTypes);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }

        close(rs,ps,con);

        return typeMap;
    }

    public static void close(ResultSet rs, PreparedStatement ps, Connection con){
        try {
            if(rs!=null){
                rs.close();
            }
            if(ps!=null){
                ps.close();
            }
            if(con!=null){
                con.close();
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
}
